"use client"
import { useState,useEffect } from "react";
import { useRouter } from "next/navigation";
import baseService from "@/service/baseService";
import Loader from "@/components/Loader";


export default function SubPage() {
    const [errorMsg,setErrorMsg] = useState("");
    const [username,setUsername] = useState("");
    const [actPlan,setActPlan] = useState({});
    const [loading,setLoading] = useState(true);
    const [paying,setPaying] = useState(false);
    const [skuList,setSkuList] = useState([]);
    const [actSku,setActSku] = useState({});

    async function loadSkuList(spuId,stockTargetId){
        return (await baseService.skuList({spuId,stockTargetId})).data;
    }

    async function loadData(plan){
        let { spuId,stockId } = plan;
        let skuListResult = await loadSkuList(spuId,stockId);
        setSkuList(skuListResult);
        actSkuHandler(skuListResult[0])
        setLoading(false)
    }
    
    function actSkuHandler(sku){
        setActSku(sku)
    }


    async function payHandler(payChannel){
        setPaying(true)
        let params = {
            skuId: actSku.id,
            paymentChannel: payChannel
        }
        let result = await baseService.pay(params);
        if(result.success){
            payJump(payChannel,result.data);
        }else{
            setPaying(false)
            setErrorMsg(result.msg);
        }

    }

    function payJump(channel,data){
        if("ALIPAY" === channel){
            const div = document.createElement('divform');
            div.innerHTML = data; // data就是接口返回的form 表单字符串
            document.body.appendChild(div);
            let len = document.forms.length - 1;
            document.forms[len].submit();
        }
    }

    function subtractAndFormat(a, b) {
        const result = a - b;
        // 检查结果是否为整数
        if (Number.isInteger(result)) {
          return result; // 如果是整数，返回原值
        } else {
          return result.toFixed(2); // 如果有小数，保留两位并四舍五入
        }
    }

    useEffect(() => {
        setLoading(true)
        let plan = JSON.parse(window.localStorage.getItem("PLAN"));
        setUsername(window.localStorage.getItem("USERNAME"));
        setActPlan(plan);
        loadData(plan);
    },[])

    return (
        <main className="relative min-h-full bg-white">
            <div className="w-full min-h-full">
                <header className="w-full h-12 md:h-20  mx-auto flex items-center border-b px-2 lg:px-10 md:px-20 ">
                    <a className="w-20 md:w-32 lg:w-44" href="https://ok123.shop">
                        <img src="Netflix_Logo_PMS.png"/>
                    </a>
                    <div className="flex-1 text-right flex items-center gap-2 w-full justify-end pr-3 xl:pr-0">
                        <p className="text-gray-500">{username}</p>
                        <a href="/" className="mya text-sm">注销</a>
                    </div>
                </header>
            </div>
            <div className="max-w-xl w-full mx-auto pt-10 px-4 md:px-2 lg:px-0">
                <p>第 3/3 步<a className="mya" href="/sub">重新选择方案</a></p> 
                <h2 className="text-lg md:text-4xl font-bold my-2 md:my-4">请选择您的购买时长和付款方式</h2>

                <div className={`default-ltr-cache-hljwm5 ${actPlan.id === 1 ? 'plana' : actPlan.id === 2 ? 'planb' : 'planc'} !m-0`}>
                    <p className="text-white text-2xl font-bold">{actPlan.title}</p>
                    <p className="text-sm">{actPlan.content}</p>
                    <div className="flex justify-end pt-2">
                        <svg width="14" height="14" viewBox="0 0 24 22" fill="none" className="success-icon" data-uia="success-svg">
                            <path fillRule="evenodd" clipRule="evenodd" d="M12.0183 21.0833C17.7761 21.0833 22.4438 16.5688 22.4438 11C22.4438 5.43112 17.7761 0.916656 12.0183 0.916656C6.26044 0.916656 1.59277 5.43112 1.59277 11C1.59277 16.5688 6.26044 21.0833 12.0183 21.0833ZM11.7407 14.3982L17.4273 8.89817L16.087 7.60181L11.0705 12.4536L8.89738 10.3518L7.55702 11.6482L10.4004 14.3982L11.0705 15.0463L11.7407 14.3982Z" 
                            fill="#fff"></path>
                        </svg>
                    </div>
                </div>

                {
                    loading ? (
                        <div className="py-40 flex flex-col justify-center items-center bg-zinc-700 bg-opacity-10 mt-4 rounded-lg gap-4">
                            <Loader/>
                            方案加载中...
                        </div>
                    ) : 
                    (
                        <>
                            <div className="flex flex-col gap-2 mt-4">
                                {
                                    skuList.map(item => (
                                        <div key={item.id} className={`
                                            p-4 border rounded-lg text-gray-600 cursor-pointer  
                                            ${actSku.id === item.id ? 'border-blue-300 border-2 act-sku' : null}
                                        `} onClick={e => actSkuHandler(item)}>
                                            <h3 className="text-gray-900 flex items-center"><p className="flex-1">{item.title}</p> <span className="text-sm">{item.value}天</span></h3>
                                            <div className="flex items-center">
                                                <p className={`flex-1 ${actSku.id === item.id ? 'text-red-500 font-bold' : null}`}><span className={`text-xl `}>{item.salePrice}</span>元 </p>
                                                {
                                                    item.originalPrice - item.salePrice >  0 ? 
                                                    (<p><span className="text-sm">已优惠</span><span className="pl-2 text-xl">{subtractAndFormat(item.originalPrice , item.salePrice)}</span>元</p>)
                                                    :
                                                    null
                                                }
                                                
                                            </div>
                                        </div>
                                    ))
                                }
                               
                            </div>
                            <div className="relative left-0 bottom-0  flex flex-col gap-2 mt-4 h-14 w-full">
                            
                                
                                {
                                    paying ? (
                                        <button className="bg-red-400 px-6 rounded-md font-bold h-full text-white  w-full flex items-center justify-center gap-2">
                                            <Loader/>
                                        </button>
                                    ) : 
                                    (
                                        <button className="bg-red-600 px-6 rounded-md font-bold active:bg-red-500 h-full text-white  w-full flex items-center justify-center gap-2" onClick={e => payHandler("ALIPAY")}>
                                            <img className="w-6" src="alipay.png"/>
                                            支付宝支付
                                        </button>
                                    )
                                }
                            </div>
                            
                            {
                                errorMsg ? 
                                (<p className="mt-5 text-red-500 text-lg font-bold">
                                    出错了：{errorMsg}
                                </p>)
                                :
                                null
                            }
                            <p className="mt-5 text-gray-400 text-sm pb-10 mb-10">
                                所有账号均是4K高级账号，并且都支持所有设备登陆，可以同户验证，自助获取验证码信息，付款之后，将会在 <a className="mya" href="https://ok123.shop/mine/sub">我的订阅</a>中查看到您的账号信息，同时也会发账号信息到您注册的
                                <a className="mya">短信或邮件</a>
                                中。
                            </p>
                        </>
                    )
                }
            </div>

        </main>
    );
}
